var app = getApp()
var util = require('../../../utils/util.js');
var netWork = require('../../../utils/netutil.js');
var config = require('../../../utils/config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    flightInfo: null,//已选航班信息
    cabinInfo: null,//已选仓位信息
    passengerArr: new Array(),//乘机人
    approveArr: new Array(),//审批人
    linkMan: '',
    payType: 0,//支付方式。默认勾选公司支付
    showDetail: false,//是否显示明细，默认不显示
    showInsurance: false,//是否显示保险,默认不显示
    startDate: '',
    endDate: '',
    linkManInfo: new Object(),//联系人信息
    onBusinessReason: '',//出差原因
    insuranceArr: new Array(),//保险数组
    insuranceMid: new Array(),//保险勾选中间替换数组
    SettlementType: 1,//订单结算方式(1个人：现付 2公司：预存款)默认为公司支付1.
    checkCompany: true,//公司支付
    checkSelf: false,//个人支付
    SerFee: 0,//服务费
    reasonStr:'',
    IsOverStandard:false,
    OverStandardType:0,
    totalMoney:0,//总金额
    //成功页需要
    orderNo:'',
    money:'',
    showApproveView:true,//是否显示选择审批人视图。默认显示

    //'&reasonStr=' + reasonStr + '&IsOverStandard=' + IsOverStandard + '&OverStandardType=' + OverStandardType
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //接收传值，
    that.data.SerFee = options.SerFee;
    var flightInfo = JSON.parse(options.flightInfo);
    var cabinInfo = JSON.parse(options.cabinInfo);
    console.log(flightInfo);
    console.log(cabinInfo);
    var startDate = '';
    var endDate = '';
    var endDateA = flightInfo.ArriveDate.split('T');
    var startDateA = flightInfo.TakeOffDate.split('T');
    startDate = startDateA[0];
    endDate = endDateA[0];

    that.data.reasonStr = options.reasonStr;
    that.data.IsOverStandard = options.IsOverStandard;
    that.data.OverStandardType = options.OverStandardType;

    //week.
    var startWeek = util.getTheDateWeek(startDate);
    var endWeek = util.getTheDateWeek(endDate);

    //获取保险
    that.loadTheUrlForInsuranceInfo();

    //联系人信息
    var name = app.globalData.TUserInfo.TrueName != null ? app.globalData.TUserInfo.TrueName : '';
    var phone = app.globalData.TUserInfo.UserName != null ? app.globalData.TUserInfo.UserName : '';
    var email = app.globalData.TUserInfo.Email != null ? app.globalData.TUserInfo.Email : '';
    that.data.linkManInfo.name = name;
    that.data.linkManInfo.phone = phone;
    that.data.linkManInfo.email = email;

    console.log('是否需要审批');
    console.log(app.globalData.TUserInfo.IsNeedFlightApprove);

    wx.setNavigationBarTitle({
      title: flightInfo.StartPortName + '-' + flightInfo.EndPortName,
    })

    //set data
    that.setData({
      flightInfo: flightInfo,
      cabinInfo: cabinInfo,
      startDate: startDate + ' ' + startWeek,
      endDate: endDate + ' ' + endWeek,
      linkManInfo: that.data.linkManInfo,
      showApproveView: app.globalData.TUserInfo.IsNeedFlightApprove,
    })
    console.log(flightInfo.EndPortName);
    // console.log(util.logObject(cabinInfo));
  },

  //请求保险接口获取保险数据
  loadTheUrlForInsuranceInfo: function () {
    var that = this;
    that.showLoading();

    var postDic = new Object();
    postDic.SiteID = app.globalData.TUserInfo.SiteID;//站点ID
    postDic.EID = app.globalData.TUserInfo.EID;//企业ID(必填 计算返佣时需要)
    postDic.Category = 0;//保险分类（0国内保险 1国际保险 2火车票保险）
    postDic.StartDate = that.data.startDate;

    var url = config.getBaseUrl('InsuranceApi', 'GetProduct');
    netWork.post(
      url,
      postDic,
      function (res) {//success
        wx.hideLoading()
        console.log('保险接口');
        console.log(res.data);
        if (res.data == null) {
          return;
        }
        var insuranceArr = new Array();
        if(res.data.Data != null) {
          insuranceArr = res.data.Data.DataProduct;
        }
        
        for (var i = 0; i < insuranceArr.length; i++) {
          insuranceArr[i].select = false;
        }
        
        //刷新列表
        that.setData({
          insuranceArr: insuranceArr,
        })
      },
      function (res) {//fail
        wx.hideLoading()
      }
    )
  },
  //show request loading..
  showLoading: function () {
    wx.showLoading({
      title: '加载中...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 6000)
  },
  //创建请求列表数据所需的postDic
  preparePostDic: function () {
    var that = this;
    var postDic = new Object();
    var totalMoney = that.calculateTheTotalMoney();
    //1.base data
    postDic.UserID = app.globalData.TUserInfo.UserID;////下单者用户ID 即企业员工
    postDic.OrderFromTerminal = 5;// 订单来源终端(0 OA导单 1企业差旅前台  2安卓客户端   3苹果客户端  4 H5   5 微信小程序 9 其他 )
    postDic.TravelType = 0;/// 差旅类型 (对应枚举TravelType值 0因公 , 1因私 ) 。 （必填）
    postDic.SettlementType = that.data.checkCompany == true ? 2 : 1;//订单结算方式（对应枚举SettlementType值 1个人：现付 2公司：预存款 3月结） 
    postDic.TravelReason = that.data.onBusinessReason; //出差事由
    postDic.FlightType = 0; // //订单航程类型（0单程 1往返 2联程）
    postDic.OrderAmount = totalMoney; //订单总金额(所有金额之和)
    postDic.IsPnrOrRTImport = false; // 是否是PNR导入订单
    postDic.ContactName = that.data.linkManInfo.name; ////联系人姓名
    postDic.ContactMobile = that.data.linkManInfo.phone;//联系人手机号
    postDic.ContactEmail = that.data.linkManInfo.email; //联系人 邮箱（选填）
    postDic.IsOverStandard = that.data.IsOverStandard;
    postDic.OverStandardType = that.data.OverStandardType;
    postDic.OverStandardRemark = that.data.reasonStr;

    // //2.审批人LstApproveUserIDs
    var approveArr = new Array();
    for (var i = 0; i < that.data.approveArr.length; i++) {
      var id = that.data.approveArr[i].UserID;
      approveArr.push(id);
    }
    postDic.LstApproveUserIDs = approveArr;

    //2.FlightPrice
    var FlightPrice = new Object();
    FlightPrice.AdultRealFare = that.data.cabinInfo.RealFare;// 成人真实票面 (如果是往返或联程为两段的组合总的票面价)
    FlightPrice.AdultTax = that.data.flightInfo.Tax;//成人机建(如果是往返或联程为两段的总的基建) （必填）
    FlightPrice.AdultOil = that.data.flightInfo.Oil;//  成人燃油(如果是往返或联程为两段的总的燃油)（必填）
    FlightPrice.ChildRealFare = 0;// 儿童真实票面 (如果是往返或联程为两段的组合总的票面价) 乘机人没有儿童时传0即可
    FlightPrice.ChildTax = 0;//儿童机建(如果是往返或联程为两段的总的基建) 乘机人没有儿童时传0即可
    FlightPrice.ChildOil = 0;// 儿童燃油(如果是往返或联程为两段的总的基建) 乘机人没有儿童时传0即可
    FlightPrice.BabyRealFare = 0; // 婴儿真实票面 (如果是往返或联程为两段的组合总的票面价) 乘机人没有婴儿时传0即可
    FlightPrice.BabyTax = 0;// 婴儿机建(如果是往返或联程为两段的总的基建) 乘机人没有婴儿时传0即可
    FlightPrice.BabyOil = 0; // 婴儿燃油(如果是往返或联程为两段的总的燃油) 乘机人没有婴儿时传0即可

    postDic.FlightPrice = FlightPrice;

    //3.OrderFlights
    var orderFlights = new Array();
    var orderFlightsInfo = new Object();
    orderFlightsInfo.SAirportCode = that.data.flightInfo.StartCode;//出发机场三字码
    orderFlightsInfo.SAirportName = that.data.flightInfo.StartPortName;//出发机场名称
    orderFlightsInfo.SCityName = app.globalData.fromCity.CityName;;//出发城市名称(必填)。 
    orderFlightsInfo.EAirportCode = that.data.flightInfo.EndCode;//到达机场三字码
    orderFlightsInfo.EAirportName = that.data.flightInfo.EndPortName;//到达机场名称
    orderFlightsInfo.ECityName = app.globalData.toCity.CityName;//到达城市名
    orderFlightsInfo.STerminal = that.data.flightInfo.StartT;//出发航展楼
    orderFlightsInfo.ETerminal = that.data.flightInfo.EndT;//到达航展楼
    orderFlightsInfo.BeginDate = that.data.flightInfo.TakeOffDate;//出发日期
    orderFlightsInfo.BeginTime = that.data.flightInfo.OffTime;//出发时间
    orderFlightsInfo.ArriveDate = that.data.flightInfo.ArriveDate;//到达时间
    orderFlightsInfo.ArriveTime = that.data.flightInfo.ArriveTime;//到达时间
    orderFlightsInfo.Cabin = that.data.cabinInfo.Cabin;//舱位
    orderFlightsInfo.CabinName = that.data.cabinInfo.CabinName;//舱位名称
    orderFlightsInfo.FlightNo = that.data.flightInfo.FlightNo;//C1983
    orderFlightsInfo.AirLineName = that.data.flightInfo.CarrinerName;//中国国航
    orderFlightsInfo.PlaneType = that.data.flightInfo.PlaneType;//机型
    orderFlightsInfo.Distance = that.data.flightInfo.Distance;//距离
    orderFlightsInfo.C02 = '';//二氧化碳量
    orderFlightsInfo.Discount = that.data.cabinInfo.Discount;//折扣

    orderFlights.push(orderFlightsInfo);
    postDic.OrderFlights = orderFlights;//创单所需航班信息

    //4.乘机人
    var passengerArr = new Array();
    for (var i = 0; i < that.data.passengerArr.length; i++) {
      var passengerDic = new Object();
      passengerDic.PsgName = that.data.passengerArr[i].CName;
      passengerDic.CardType = that.data.passengerArr[i].CardType;
      passengerDic.CardNo = that.data.passengerArr[i].CardNo;
      var birthday = that.data.passengerArr[i].BirthDay.split('T')[0];
      passengerDic.BirthDay = birthday;
      passengerDic.Mobile = that.data.passengerArr[i].Mobie == null ? '' : that.data.passengerArr[i].Mobie;
      passengerDic.PsgType = 0;

      //保险..
      var insuranceStr = '';
      var spaceStr = '';
      for (var i = 0; i < that.data.insuranceArr.length; i++) {
        if (that.data.insuranceArr[i].select == true) {
          if(insuranceStr.length == 0) {
            spaceStr = '';
          }else {
            spaceStr = ',';
          }
          insuranceStr = insuranceStr + spaceStr + that.data.insuranceArr[i].ProductCode + ',';
        }
      }
      passengerDic.IsuProductCodes = insuranceStr;
      passengerArr.push(passengerDic);
    }
    postDic.Passengers = passengerArr;
    console.log('国内机票postDic');
    console.log(postDic);
    return postDic;
  },
  //计算总价
  calculateTheTotalMoney: function () {
    var that = this;
    var totalMoney = 0;
    //乘机人(全部为成人,人数直接相乘)
    var passengerCount = that.data.passengerArr.length;

    //票价
    var ticketPrice = that.data.cabinInfo.RealFare;
    var Tax = that.data.flightInfo.Tax;
    var Oil = that.data.flightInfo.Oil;
    ticketPrice = (ticketPrice + Tax + Oil) * passengerCount;

    //服务费:SerFee
    var serfee = that.data.SerFee;
    serfee = serfee * passengerCount;

    //保险费
    var insurancePrice = 0;
    var insuranceP = 0;
    var insuranceArr = that.data.insuranceArr;
    for (var i = 0; i < insuranceArr.length; i++) {
      if (insuranceArr[i].select == true) {
        insuranceP = insuranceP + insuranceArr[i].SalePrice;
      }
    }
    insurancePrice = insuranceP * passengerCount;
    console.log('1:' + ticketPrice + '2:' + serfee + '3:' + insurancePrice);
    totalMoney = ticketPrice + serfee + insurancePrice;

    that.setData({
      totalMoney:totalMoney,
    })
    return totalMoney;
  },
  //明细信息
  setupDetailInfo: function () {
    var that = this;
    var totalMoney = 0;
    //乘机人(全部为成人,人数直接相乘)
    var passengerCount = that.data.passengerArr.length;

    //票价
    var ticketPrice = that.data.cabinInfo.RealFare;
    var Tax = that.data.flightInfo.Tax;
    var Oil = that.data.flightInfo.Oil;

    //服务费:SerFee
    var serfee = that.data.SerFee;
    serfee = serfee * passengerCount;

    //保险费
    var insurancePrice = 0;
    var insuranceP = 0;
    var insuranceArr = that.data.insuranceArr;
    console.log('baoxian');
    console.log(insuranceArr);
    for (var i = 0; i < insuranceArr.length; i++) {
      if (insuranceArr[i].select == true) {
        insuranceP = insuranceP + insuranceArr[i].SalePrice;
      }
    }

    var detailInfoArr = new Array();
    var detailInfoDic = new Object();
    detailInfoDic.name = '成人票';
    detailInfoDic.priceStr = ticketPrice + 'x' + passengerCount;
    detailInfoArr.push(detailInfoDic);

    if (Tax > 0 || Oil > 0) {
      var taxOilDic = new Object();
      taxOilDic.name = '机建/燃油';
      taxOilDic.priceStr = (Tax + Oil) + 'x' + passengerCount;
      detailInfoArr.push(taxOilDic);
    }

    //保险费
    var serveArr = new Array();
    if (insuranceP > 0) {
      var insuranceDic = new Object();
      insuranceDic.name = '保险费';
      insuranceDic.priceStr = insuranceP + 'x' + passengerCount;
      serveArr.push(insuranceDic);
    }
    //服务费
    if (serfee > 0) {
      var serFeeDic = new Object();
      serFeeDic.name = '服务费';
      serFeeDic.priceStr = serfee + 'x' + passengerCount;
      serveArr.push(serFeeDic);
    }
    console.log(detailInfoArr);
    console.log(serveArr);
    console.log(insuranceP);
    console.log(serfee);
    that.setData({
      ticketDetailArr: detailInfoArr,
      serDetailArr: serveArr,
    })
  },
  //显示明细
  showDetail: function (event) {
    var that = this;
    console.log(!that.data.showDetail);
    if (!that.data.showDetail) {//显示
      that.setupDetailInfo();
    }
    that.setData({
      showDetail: !that.data.showDetail,
    })
  },
  //点击保险
  insuranceTap: function () {
    var that = this;
    //赋值
    that.data.insuranceMid = that.data.insuranceArr;
    that.setData({
      insuranceMid: that.data.insuranceMid,
      showInsurance: !that.data.showInsurance
    })
  },
  //点击了保险项..
  selectInsurance: function (res) {
    var that = this;
    var index = res.currentTarget.dataset.index;
    that.data.insuranceMid[index].select = !that.data.insuranceMid[index].select;
    console.log(index + ':' + that.data.insuranceMid[index].select);
  },
  //保险取消
  insuranceCancel: function () {
    var that = this;
    that.setData({
      showInsurance: false
    })
  },
  //保险确定
  insuranceSure: function () {
    var that = this;
    //确定中间值刷新数据源
    that.data.insuranceArr = that.data.insuranceMid;
    console.log(that.data.insuranceArr);

    //刷新TotalMoney
    var totalMoney = that.calculateTheTotalMoney();
    that.setData({
      showInsurance: false
    })
  },

  /**                                MARK -- 乘机人
   ***************************************************************************** 
   *****************************************************************************
   */
  //选择乘机人
  passenger: function () {
    var that = this;
    //选择乘机人页要求传值.
    app.globalData.tempData = that.data.passengerArr;
    //type 0火车票 1机票
    wx.navigateTo({
      url: '../../passenger/passengerSelect/passengerSelect?type=' + 1,
    })
  },
  success: function (orderNo, money) {
    wx.redirectTo({
      url: '../../success/success?orderN=' + orderNo + '&money=' + money + '&paytype=' + 1 + '&resultType=' + 0
    })
    /*    var ticketType = options.paytype;//票类型：1：飞机，0：火车
          var fromType = options.resultType;//结果类型：0：下单，1：支付
     */
  },
  ///选择乘机人回调函数
  updateData: function (res) {
    var that = this;
    console.log('乘机人');
    console.log(res);
    // for (var i = 0;i < res.length;i++) {
    //   that.data.passengerArr.push(res[i]);
    // }

    //刷新data
    that.setData({
      passengerArr: res,
    })
    //刷新TotalMoney
    var totalMoney = that.calculateTheTotalMoney();
  },
  //删除乘机人
  deleteMySelf: function (event) {
    var that = this;
    var index = event.currentTarget.dataset.index;
    console.log('delete');
    that.data.passengerArr.splice(index, 1);
    that.setData({
      passengerArr: that.data.passengerArr,
    })
    that.calculateTheTotalMoney();
  },

  /**                                MARK -- 审批人
   ***************************************************************************** 
   *****************************************************************************
   */
  /**
   * 选择审批人回调函数(approve)
   * res:审批人数组
   */
  updateApproveData: function (res) {
    var that = this;

    that.setData({
      approveArr: res,
    })
    //刷新TotalMoney
    var totalMoney = that.calculateTheTotalMoney();
  },
  //选择审批人
  approver: function () {
    var that = this;
    //传已选择审批人数组，，应对方要求所有传值都通过同一个全局对象传递。（app.globalData.tempData）
    app.globalData.tempData = that.data.approveArr;

    wx.navigateTo({
      url: '../../approver/department/department',
    })
  },
  //删除审批人
  deleteApprover: function (res) {
    var that = this;
    var index = res.currentTarget.dataset.index;
    that.data.approveArr.splice(index, 1);
    that.setData({
      approveArr: that.data.approveArr,
    })
  },
  //出差原因
  textChange: function (res) {
    var that = this;
    that.data.onBusinessReason = res.detail.value;
  },
  //联系人
  contactPerson: function () {
    var that = this;
    wx.navigateTo({
      url: '../../contactPerson/contactPerson?linkManInfo=' + JSON.stringify(that.data.linkManInfo),
    })
  },
  payType: function (res) {
    var that = this;
    var type = res.currentTarget.dataset.type;
    if (type == 'company') {
      that.setData({
        checkCompany: true,
        checkSelf: false
      })
    } else if (type == 'self') {
      that.setData({
        checkCompany: false,
        checkSelf: true
      })
    }
  },
  //提交订单
  submitOrder: function () {
    var that = this;
    //非空验证
    if (that.data.passengerArr.length == 0) {
      wx.showToast({
        title: '请选择乘机人',
      })
      return;
    }
    if (that.data.approveArr.length == 0 && (that.data.showApproveView == true)) {
      wx.showToast({
        title: '请选择审批人',
      })
      return;
    }
    if (that.data.onBusinessReason.length == 0) {
      wx.showToast({
        title: '请填写出差原因',
      })
      return;
    }
    that.showLoading();

    var postData = that.preparePostDic();
    var url = config.getBaseUrl('FlightApi', 'CreateOrder');
    netWork.post(
      url,
      postData,
      function (res) {//success
        wx.hideLoading()
        console.log('order:::');
        console.log(res.data);

        if (res.data.Data == null) {
          wx.showToast({
            title: res.data.ResponseMetaInfo.Reason,
          })
        } else {
          var orderNo = res.data.Data.OrderNo;
          var pnr = res.data.Data.Pnr;
          if(pnr == null || pnr.length == 0) {
            wx.showToast({
              title: res.data.Data.Desc,
            })
          }else {
            that.success(orderNo,that.data.totalMoney);
          }
        }
      },
      function (res) {//fail
        wx.hideLoading()
        wx.showToast({
          title: '网络错误',
        })
      }
    )
  }
})